import os,yaml
#编辑文件初始化
class edit_data_class:
    @classmethod
    def init_base_js(cls,base_config):
        
        str_js=''
        file_lst=[]

        # 使用os.walk()遍历文件夹  
        for root, dirs, files in os.walk(base_config['base_js_dir']):  
            for file in files:  
                # 检查文件是否以.js结尾  
                if file.endswith('.js'):  
                    # 构造文件的完整路径并添加到列表中  
                    file_path = os.path.join(root, file)  
                    file_lst.append(file_path) 
        lst_dir=sorted(file_lst,key=lambda item:int(os.path.basename(item).split('_')[0]) )
        for path in lst_dir:
            try:
                with open(path,'r',encoding='utf-8')as f:
                    str_js=str_js+'\n'+f.read()
            except Exception as e:print(e)
        with open(base_config['static_dir']+os.sep+'base.js','w',encoding='utf-8')as f:
            f.write(str_js)
    @classmethod
    def init_base_css(cls,base_config):
        
        str_css=''
        file_lst=[]

        # 使用os.walk()遍历文件夹  
        for root, dirs, files in os.walk(base_config['base_css_dir']):  
            for file in files:  
                # 检查文件是否以.js结尾  
                if file.endswith('.css'):  
                    # 构造文件的完整路径并添加到列表中  
                    file_path = os.path.join(root, file)  
                    file_lst.append(file_path) 
        for path in file_lst:
            try:
                with open(path,'r',encoding='utf-8')as f:
                    str_css=str_css+'\n'+f.read()
            except Exception as e:print(e)
        with open(base_config['static_dir']+os.sep+'base.css','w',encoding='utf-8')as f:
            f.write(str_css)
    def 获取基础组件数据(self):
        return {
            "flow_chat_componen":self.获取_后端_基础流程图组件()
        }
    def __init__(self,base_config):
        self.base_config=base_config
        self.data={}
        self.step0_获取基础vue组件()
        self.step1_数据库设置()
        self.step2_数据库设置_htmlcrud()
        self.step3_页面设置_新增页面()
        self.step4_页面编辑_骨架()
        self.step5_页面编辑_组件()
        self.step6_页面编辑_htmlcrud()
        self.step7_后端_新增流程()
    def step7_后端_新增流程(self):
        
      self.data['new_flow_chat']={   
                                      "flow_chat_name": { 
                                      'ch_name':'流程名称',
                                      "default": '  ',  
                                      "type": "text"  
                                      },  
                                      "info": {  
                                      'ch_name':'备注',
                                      "default": "",  
                                      "type": "text"  
                                      }  
                                      }
    def _get_folder_paths2(self,dir_path):
        folder_paths = []  
        for root, dirs, files in os.walk(dir_path):  
            # print(dirs,1,root)
            for dir in dirs:
                # print(os.path.exists(r"e:\klkl\klkl\work_space(4)\easy_edit\\_web\base_vue_template\页面编辑_被拖拽的组件1\0_页面骨架\1000_纵向骨架1\main.yaml"))
                # print(root+os.sep+dir+os.sep+"main.yaml")
                if os.path.exists(root+os.sep+dir+os.sep+"main.js"):
                    folder_paths.append(root+os.sep+dir)  # 将当前目录的完整路径添加到列表中  
        return folder_paths
    def 获取_后端_基础流程图组件(self):
        res={
          'now_load_flow_chat_componen':[],#后端_基础流程图组件
          'other_flow':[],#当前项目正在加载的 流程图组件
          }

        #读取 存放后端_基础流程图组件 的文件夹
        dir_path=self.base_config['flow_dir']+os.sep+'a1'
        flow_dir1=["a1"]
        #遍历所有一级目录
        for item in os.listdir(dir_path):
            #读取一级目录配置 0 拼接配置文件的路径
            flow_dir2=[_ for _ in flow_dir1]+[item]#基础目录名(0)+一级目录名(0,1,2,3...这种) [0,0]
            yaml_file_path=os.path.join(dir_path,item,"main.yaml")
            #读取一级目录配置 -2 创建存放该目录下所有数据的字典{"name":xxx,"child":[]}
            dir1_dct={"name":"null","child":[]}
            #读取一级目录配置 -3 如果没有配置 则不加载读取
            if os.path.exists(yaml_file_path):
                with open(yaml_file_path, 'r',encoding='utf-8') as f:
                    yaml_val = yaml.load(f, Loader=yaml.FullLoader)
                    #读取一级目录配置 -4 获取一级目录名称
                    dir1_dct['name']=yaml_val['name']
            else:
                continue
            #遍历所有二级目录
            dir1_path=dir_path+os.sep+item
            for item2 in os.listdir(dir1_path):
                # [-1,0,0]
                flow_dir3=[_ for _ in flow_dir2]+[item2]#基础目录名(0）+一级目录名(0,1,2,3...这种) +二级目录名(0,1,2,3...这种)
                dir2_dct={"name":"null","child":[]} 
                #读取二级目录配置 -1 拼接配置文件的路径
                dir2_path=os.path.join(dir1_path, item2)
                yaml_path=os.path.join(dir2_path,"main.yaml")
                #读取二级目录配置 -2 如果没有配置 则不加载读取
                if os.path.exists(yaml_path):
                    with open(yaml_path, 'r',encoding='utf-8') as f:
                        yaml_val2 = yaml.load(f, Loader=yaml.FullLoader)
                else:
                    continue
                dir2_dct['name']=yaml_val2['name']#二级目录名称
                for item3 in os.listdir(dir2_path):
                    #读取组件配置 -1 拼接配置文件的路径
                    yaml_path2=os.path.join(dir2_path, item3,"main.yaml")
                    if os.path.exists(yaml_path2):
                        with open(yaml_path2, 'r',encoding='utf-8') as f:
                            yaml_path2_val = yaml.load(f, Loader=yaml.FullLoader)
                    else:
                        continue
                    # print(yaml_path2)
                    temp_name=yaml_path2_val['name']#组件名称
                    version=str(yaml_path2_val['index'])#当前组件的最高版本
                    flow_dir=[_ for _ in flow_dir3]+[item3,version]
                    #加载最高版本的组件数据
                    flow_dct={"name":temp_name,"max_version":version,"version":version,"flow_dir":flow_dir}
                    flow_yaml=os.path.join(dir2_path, item3,'history',version,'main.yaml')
                    # print(flow_yaml,1)
                    #读取组件配置 -2 如果没有配置 则不加载读取
                    if os.path.exists(flow_yaml):
                        with open(flow_yaml, 'r',encoding='utf-8') as f:
                            yaml_val3 = yaml.load(f, Loader=yaml.FullLoader)
                        flow_dct.update(yaml_val3)
                        dir2_dct['child'].append(flow_dct)
                        # print(3,yaml_val3)
                if (dir2_dct['child']!=[]):
                    dir1_dct['child'].append(dir2_dct)
            if (dir1_dct['child']!=[]):
                res['now_load_flow_chat_componen'].append(dir1_dct)
        return res
    def step0_获取基础vue组件(self):
        #生成基础vue组件的js文件和css文件
        str_js=''
        str_css=''
        file_lst=self._get_folder_paths2(self.base_config['base_vue_template'])
        # print(file_lst)
        lstdir=sorted(file_lst,key=lambda item:int(os.path.basename(item).split('_')[0]) )
        for new_dir_path in lstdir:
            try:
                with open(new_dir_path+os.sep+'main.js','r',encoding='utf-8')as f:
                    str_js=str_js+'\n'+f.read()
            except Exception as e:pass
            try:
                with open(new_dir_path+os.sep+'main.css','r',encoding='utf-8')as f:
                    str_css=str_css+'\n'+f.read()
            except Exception as e:pass
        with open(self.base_config['static_dir']+os.sep+'base_vue_template.js','w',encoding='utf-8')as f:
            f.write(str_js)

        with open(self.base_config['static_dir']+os.sep+'base_vue_template.css','w',encoding='utf-8')as f:
            f.write(str_css)
        ########mbase.js
        str_js=''
        file_lst=[]

        # 使用os.walk()遍历文件夹  
        for root, dirs, files in os.walk(self.base_config['base_js_dir']):  
            for file in files:  
                # 检查文件是否以.js结尾  
                if file.endswith('.js'):  
                    # 构造文件的完整路径并添加到列表中  
                    file_path = os.path.join(root, file)  
                    file_lst.append(file_path) 
        lst_dir=sorted(file_lst,key=lambda item:int(os.path.basename(item).split('_')[0]) )
        for path in lst_dir:
            try:
                with open(path,'r',encoding='utf-8')as f:
                    str_js=str_js+'\n'+f.read()
            except Exception as e:print(e)
        with open(self.base_config['static_dir']+os.sep+'base.js','w',encoding='utf-8')as f:
            f.write(str_js)
    def step1_数据库设置(self):
        # 数据库 新增字段【表单信息】
        self.data['table_field_info']={ 
  "名称": {  
    "default": "",  
    "type": "text",  
    "备注": "字段的名字"  
  },  
  "备注": {  
    "default": "",  
    "type": "text",  
    "备注": "字段的详细说明"  
  },  
  "主键": {  
    "default": False,  
    "type": "bool",  
    "备注": "是否为自增长,创建数据库时定义是否为主键"  
  },  
  "自增长": {  
    "default": False,  
    "type": "bool",  
    "备注": "是否为自增长,创建数据库时定义是否为自增长"  
  },  
  "索引": {  
    "default": False,  
    "type": "bool",  
    "备注": "是否为索引,创建数据库时定义是否为索引"  
  },  
  "唯一索引": {  
    "default": False,  
    "type": "bool",  
    "备注": "是否为唯一索引,创建数据库时定义是否为唯一索引"  
  },  
  "字段类型": {  
    "default": "INTEGER",  
    "type": "select",  
    "type_dct": "[\"INTEGER\",\"TEXT\",\"DATETIME\",\"VARCHAR\"]",  
    "备注": "字段的类型,创建数据库时定义字段类型"  
  },  
  "字段长度": {  
    "default": None,  
    "type": "minmax",  
    "备注": "字段的长度,创建数据库时定义字段长度"  
  },  
  "update_modify_time": {  
    "default": False,  
    "type": "bool",  
    "备注": "是否自动更新时间(DATETIME字段类型),创建数据库时设置触发器在数据被更新时自动更新该字段为最新时间"  
      }  }
        # 数据库 新增数据库的字段【表单信息】
        self.data['table_base_info']={
            'en_name':{'ch_name':'数据库名(英文)',"default":"db_name","type":"text"},
            'ch_name': {'ch_name':'数据库名(中文)','default':'','type':'text'},
            'info': {'ch_name':'备注','default':'','type':'text'},}
    def step2_数据库设置_htmlcrud(self):
      ##第三步 获取 数据库设置-htmlcrud 时的表单信息
      self.data['htmlcurd_template_info']={##数据库设置-htmlcrud   【新增参数设计
                                          'lhp_from1':{
                                              'select':
                                                  {
                                                  "edit_lhp_color":{},
                                                  "edit_lhp_img":{},
                                                  "edit_lhp_text_list":{},
                                                  "lhp_from1_edit_lhp_text":{},
                                                  }
                                                  
                                          },
                                          'lhp_login1':{
                                              'select':
                                                  {
                                                  "匹配":{},
                                                  "存储key":{},
                                                  "存储更新时间":{},
                                                  '保存选项':{}
                                      
                                                  }
                                                  
                                          },
                                          'lhp_table2':{
                                              'check':
                                                  {
                                                  "show_lhp_color":{},
                                                  "show_lhp_img":{},
                                                  "show_lhp_line":{},
                                                  "show_lhp_text":{},
                                                  "show_lhp_text_by_dict":{},
                                                  "show_lhp_xtext":{},
                                                  }
                                                  
                                          }
  
                                                  }
    def step3_页面设置_新增页面(self):  
      ##第四步 获取 页面编辑-新增页面 时的表单信息
      self.data['page_base_info']={   
                                      "page_name": { 
                                      'ch_name':'页面名称',
                                      "default": '  ',  
                                      "type": "text"  
                                      },  
                                      "url_flag": { 
                                      'ch_name':'是否使用url',
                                      "default": False,  
                                      "type": "bool"  
                                      },  
                                      "url": {  
                                      'ch_name':'url',
                                      "default": "",  
                                      "type": "text"  
                                      }  ,
                                      "info": {  
                                      'ch_name':'备注',
                                      "default": "",  
                                      "type": "text"  
                                      }  
                                      }
    def step4_页面编辑_骨架(self):
      ##第五步 获取 页面编辑-骨架  相关的信息  【单独列出只是为了在 可视化拖拽检索骨架类型组件时 提高检索速度】
      self.data['page_skeleton_params']={
                  'gu_jia_base':{
                      'type':'gu_jia',
                      'line1_class': 'gu_jia_heng_top',
                      'line2_class': 'gu_jia_heng_bottom',
                      'temp_class':'gu_jia_hong_se_heng_xian'
                  }}
      for root, dirs, files in os.walk(self.base_config['base_vue_template']):  
            dir_lst=[]
            for dir_ in dirs:
                dir_lst.append(
                    {"path":os.path.join(root, dir_),
                    "yaml_path":os.path.join(root, dir_,"main.yaml"),
                    "js_path":os.path.join(root, dir_,"main.js"),
                    # "number":  int(dir_.split("_")[0]) ,
                    }
                )
            for item in dir_lst:
                if os.path.exists(item['yaml_path']):
                    with open(item['yaml_path'], 'r',encoding='utf-8') as f:
                        yaml_val = yaml.load(f, Loader=yaml.FullLoader)
                        # print(yaml_val)
                        if yaml_val.get("type")=="gu_jia":
                            self.data['page_skeleton_params'][yaml_val['name']]={
                              'type':'gu_jia',
                              'line1_class': yaml_val['line1_class'],
                              'line2_class': yaml_val['line2_class'],
                              'temp_class':yaml_val['temp_class']
                          }

    ##第六步 获取 页面编辑-基础组件 相关的信息
    def step5_页面编辑_组件(self):
      self.data['page_componen']={
          'componen_dct':{},##{"其他组件":{"基础侧边栏":{main.yaml转json}  }}
          'componen_dct2':{},##{"vue组件名称":{main.yaml转json} }
          }

      skeleton_dir_path= os.path.join(self.base_config['base_vue_template'],'页面编辑_被拖拽的组件1')
    #   print("page_componen",skeleton_dir_path)
      #子级文件夹
      for item in os.listdir(skeleton_dir_path):
          yaml_file_path=os.path.join(skeleton_dir_path,item,"main.yaml")
          if os.path.exists(yaml_file_path):
            with open(yaml_file_path, 'r',encoding='utf-8') as f:
                yaml_val = yaml.load(f, Loader=yaml.FullLoader)
                now_com_name1=yaml_val['name']
                self.data['page_componen']['componen_dct'][now_com_name1]={}
            dir_lst=[]
            #子级文件夹下面的数据
            for root, dirs, files in os.walk(skeleton_dir_path+os.sep+item):  
                for dir_ in dirs:
                    yaml_path=os.path.join(root, dir_,"main.yaml")
                    if os.path.exists(yaml_path):
                        dir_lst.append(
                            {"path":os.path.join(root, dir_),
                            "yaml_path":os.path.join(root, dir_,"main.yaml"),
                            "js_path":os.path.join(root, dir_,"main.js"),
                            # "number":  int(dir_.split("_")[0]) ,
                            }
                        )
            # print("page_componen dir_lst",dir_lst)
            for item2 in dir_lst:
                with open(item2['yaml_path'], 'r',encoding='utf-8') as f:
                    yaml_val2 = yaml.load(f, Loader=yaml.FullLoader)
                self.data['page_componen']['componen_dct'][now_com_name1][yaml_val2['ch_name']]=yaml_val2
                componen_name=yaml_val2['name'];
                if (componen_name in self.data['page_componen']['componen_dct2']):
                    print('error 有重复的组件名！！！！ 自动覆盖前面的组件',componen_name)
                self.data['page_componen']['componen_dct2'][componen_name]=yaml_val2   
    def step6_页面编辑_htmlcrud(self):
      ##第七步 获取 页面编辑-htmlcrud 相关信息
  
        self.data['htmlcrud_componen']={
          'componen_dct':{},##{"其他组件":{"基础侧边栏":{main.yaml转json}  }}
          'componen_dct2':{},##{"vue组件名称":{main.yaml转json} }
          }
        skeleton_dir_path= os.path.join(self.base_config['base_vue_template'],'页面编辑_被拖拽的组件2-htmlcrud')
        #子级文件夹
        for item in os.listdir(skeleton_dir_path):
            yaml_file_path=os.path.join(skeleton_dir_path,item,"main.yaml")
            if os.path.exists(yaml_file_path):
              with open(yaml_file_path, 'r',encoding='utf-8') as f:
                  yaml_val = yaml.load(f, Loader=yaml.FullLoader)
                  now_com_name1=yaml_val['name']
                  
                  self.data['htmlcrud_componen']['componen_dct'][now_com_name1]={}
                  self.data['page_componen']['componen_dct']["_"+now_com_name1]={}
              #子级文件夹下面的数据
              for root, dirs, files in os.walk(skeleton_dir_path+os.sep+item):  
                dir_lst=[]
                for dir_ in dirs:
                    dir_lst.append(
                        {"path":os.path.join(root, dir_),
                        "yaml_path":os.path.join(root, dir_,"main.yaml"),
                        "js_path":os.path.join(root, dir_,"main.js"),
                        }
                    )
              for item2 in dir_lst:
                  if os.path.exists(item2['yaml_path']):
                      with open(item['yaml_path'], 'r',encoding='utf-8') as f:
                          yaml_val2 = yaml.load(f, Loader=yaml.FullLoader)

                      
                      self.data['htmlcrud_componen']['componen_dct'][now_com_name1][yaml_val2['ch_name']]=yaml_val2
                      self.data['page_componen']['componen_dct']["_"+now_com_name1][yaml_val2['ch_name']]=yaml_val2
                      componen_name=yaml_val2['name']
                      if (componen_name in self.data['htmlcrud_componen']['componen_dct2']):
                          print('error 有重复的组件名！！！！ 自动覆盖前面的组件',componen_name)
                      
                      self.data['htmlcrud_componen']['componen_dct2'][componen_name]=yaml_val2
                      self.data['page_componen']['componen_dct2'][componen_name]=yaml_val2   
if __name__=="__main__":
    pro=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    base_config={}
    def config_init():
        global base_config
        base_config['flow_dir']=pro+os.sep+os.sep+'_server'+os.sep+'flow_dir'
        base_config['now_load_flow_chat_componen']=pro+os.sep+os.sep+'_server'+os.sep+'now_load_flow_chat_componen'
        base_config['process2_web_handle']={"ip": "127.0.0.1","port": 7999}
        base_config['base_vue_template']=pro+os.sep+os.sep+'_web'+os.sep+'base_vue_template'        #vue基础组件
        base_config['base_js_dir']=pro+os.sep+os.sep+'_web'+os.sep+'base_js'        #基础js
        base_config['vue_template_store']=pro+os.sep+os.sep+'_web'+os.sep+'vue_template_store'       #vue组件商场
        base_config['static_dir']=pro+os.sep+os.sep+'_static_dir'    #存放静态文件的文件夹
        base_config['static_path']=r'\static'#tornado静态路由格式 
        base_config['pro']=pro#项目根目录
        base_config['db_dir']=os.path.dirname(pro)+os.sep+"db_dir"#存放数据库数据
        base_config['user_db_file']=os.path.dirname(pro)+os.sep+"db_dir"+os.sep+'user_db_file'#存放数据库数据-用户
        base_config['user_dir']=os.path.dirname(pro)+os.sep+"user_dir"#存放用户数据
        base_config['login']=pro+os.sep+'_web'+os.sep+'web_html'+os.sep+"login.html"   #登录页面      
        base_config['project']=pro+os.sep+'_web'+os.sep+'web_html'+os.sep+"project.html"   #登录页面      
        base_config['home']=pro+os.sep+'_web'+os.sep+'web_html'+os.sep+"home.html"   #登录页面    
    config_init()
    ed=edit_data_class(base_config)
    import json
    with open(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+os.sep+'test.yaml', 'w', encoding='utf-8') as file:  
        yaml.dump(ed.获取基础组件数据(), file, allow_unicode=True, default_flow_style=False, sort_keys=False)
    file_path=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+os.sep+'test.json'
    # data=json.dumps(ed.获取基础组件数据())
    # 将数据写入JSON文件  
    with open(file_path, 'w', encoding='utf-8') as f:  
        json.dump(ed.获取基础组件数据(), f, ensure_ascii=False, indent=4)
